﻿using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;

namespace Vkontakte.Api
{
	public sealed class Session
	{
		public long Mid { get; set; }
		public string Sid { get; set; }
		public string Secret { get; set; }
		public string Expire { get; set; }
		public string Sig { get; set; }
		public string Cookie { get; set; }
		public CookieContainer Cookies { get; set; }

		public static Session GetFromUrl(string url)
		{
			if (!url.StartsWith("http://vkontakte.ru/api/login_success.html"))
			{
				return null;
			}
			int start = url.IndexOf('{') + 1;
			int end = url.IndexOf('}');
			url = url.Substring(start, end - start);
			string[] parts = url.Split(',');
			Session ret = new Session();
			foreach (string part in parts)
			{
				string[] tmp = part.Split(':');
				string name = tmp[0].Remove(tmp[0].Length - 1, 1).Remove(0, 1);
				string value = tmp[1];
				switch (name)
				{
					case "mid":
						ret.Mid = int.Parse(value);
						break;
					case "sid":
						ret.Sid = value.Remove(value.Length - 1, 1).Remove(0, 1);
						break;
					case "secret":
						ret.Secret = value.Remove(value.Length - 1, 1).Remove(0, 1);
						break;
					case "expire":
						ret.Expire = value;
						break;
					case "sig":
						ret.Sig = value.Remove(value.Length - 1, 1).Remove(0, 1);
						break;
				}
			}
			return ret;
		}
	}
}
